﻿using System;
using System.Collections.Generic;
using System.Linq;


namespace DNUtil
{
    public static class StringUtil
    {
        public static bool IsNullOrEmpty(this string value)
        {
            return string.IsNullOrEmpty(value);
        }

        /// <summary>
        /// Returns a dictionary representing semicolon separated key/value pairs.
        /// </summary>
        /// <param name="keyValuesStr">A semicolon separated list of key/value pairs. Ex : key1=value1;key2=value2</param>
        /// <returns></returns>
        public static Dictionary<string, string> ToKeyValues(this string keyValuesStr)
        {
            if (string.IsNullOrEmpty(keyValuesStr) == false)
            {
                var pairs = keyValuesStr.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries).
                  Select(pair => pair.Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries));

                if (pairs.Count() > 0)
                {
                    var groupedPairs = pairs.GroupBy(p => p[0], StringComparer.OrdinalIgnoreCase);//in case same key is specified multiple times.
                    return groupedPairs.ToDictionary(g => g.Key, g => g.Last().Length > 1 ? g.Last()[1] : null, StringComparer.OrdinalIgnoreCase);
                }
            }

            return new Dictionary<string, string>();
        }
    }
}
